import { Bully, BullySubjectService, NotificationService, ToolsService } from 'app/shared/service';
import { BROWSER_BROADCAST, MESSAGE_CHANNEL, SYSTEM_EVENT } from 'app/app.constants';
import { TranslateService } from '@ngx-translate/core';
import { AfterViewInit, Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { Subscription } from 'rxjs';
import { ActivatedRoute } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { Map as OLMAP, View } from 'ol';
import { Circle as CircleStyle, Icon, Stroke, Style } from 'ol/style.js';
import Point from 'ol/geom/Point';
import Feature from 'ol/Feature';
import { Vector as VectorLayer } from 'ol/layer';
import { Vector as VectorSource } from 'ol/source.js';
import { easeOut } from 'ol/easing.js';
import { defaults as defaultControls, ScaleLine } from 'ol/control';
import { MapLayerService, MarkerOption } from './service/map-layer.service';
import { MapViewService } from './service/map-view.service';
import { MapClusteredService } from './service/map-clustered.service';
import { defaults as defaultInteractions } from 'ol/interaction';
import { animStyle, fadeIn, fadeOut, shrink, stretch, zoomIn, zoomOut } from 'app/animations/simple-anim';
import { animate, state, style, transition, trigger } from '@angular/animations';
import { NzMessageService, NzModalService, NzTreeNode } from 'ng-zorro-antd';
import { SystemService } from 'app/service/system.service';
import {
    ACTION_LAYER_KEY,
    BASIC_LAYER_KEY,
    CreateEvent,
    CreateEventMap,
    CreateEventOptData,
    FeatureType,
    MapDataService,
    MARKER_TYPE,
    OVERLAY_KEY
} from './service/map-data.service';
import { legendsData } from './legends/legends-data';
import { MapOverlayService } from './service/map-overlay.service';
import { LegendsComponent } from './legends/legends.component';
import { retry } from 'rxjs/operators';
import { unByKey } from 'ol/Observable.js';
import { LoginService } from 'app/auth/login.service';
import { isArray } from 'util';
import { DataManagementService } from '../../pages/data-management/data-management.services';
import { GeoJSON } from 'ol/format';
import { Text, Fill } from 'ol/style';
import { PublicService } from 'app/public/public.service';

@Component({
    selector: 'itmp-gis',
    templateUrl: './gis.component.html',
    styleUrls: ['./gis.component.css'],
    animations: [
        zoomIn,
        zoomOut,
        shrink,
        fadeIn,
        fadeOut,
        stretch,
        [
            trigger('zoomInOutNoRender', [
                state('in', style({ transform: 'translateX(0)' })),
                state('out', style({ transform: 'translateX(-280px)' })),
                transition('in <=> out', [animate(animStyle.inOutCubic)])
            ])
        ]
    ]
})
export class GisComponent implements OnInit, AfterViewInit, OnDestroy {
    @ViewChild('LegendsComponent') legendsCom: LegendsComponent;
    // legends
    showLegends = false;
    // 从获取位置的地方跳转过来
    comfrom: any;
    // 用于动画
    overlayIsShow = {
        [OVERLAY_KEY.ALERT_OVERLAY]: false,
        [OVERLAY_KEY.LOCATE_MARKER_OVERLAY]: false,
        [OVERLAY_KEY.CLUSTER_FEATURES_OVERLAY]: false,
        [OVERLAY_KEY.INCIDENT_OVERLAY]: false,
        [OVERLAY_KEY.EQUIPMENT_OVERLAY]: false
    };
    // currentCoords = [104.066011, 30.657255];
    // currentCoords = [107.085144, 20.951674]; // halong
    currentCoords = [107.085144, 20.951674];
    geoLoading = false;

    // map实例
    map: any = null;
    // map配置选项
    mapOptions: any = null;

    // 窗口控制对象
    OVERLAY_KEY = OVERLAY_KEY;

    // 图层集合
    private _layersMap: Map<string, any> = new Map<string, any>();

    // 弹出框集合
    private _overlayMap: Map<string, any> = new Map<string, any>();

    // traffic signal icons feature
    trafficSignalIconsFeature = new Feature({
        geometry: new Point([6150568, 2886161]),
        name: 'Traffic Signal',
        prototype: {
            iconSrc: 'content/images/icons/TrafficSignal.png',
            data: {
                type: 'trf',
                date: new Date()
            }
        }
    });

    newFeatures = [];

    // traffic signal icons style
    trafficSignalIconsStyle = new Style({
        image: new Icon({
            anchor: [0.5, 0.5],
            anchorXUnits: 'fraction',
            anchorYUnits: 'fraction',
            src: 'content/images/icons/TrafficSignal.png',
            scale: 0.25
        })
    });

    // google 卫星地图底图
    // googleLayerHybrid = new TileLayer({
    //     title: 'googleMap',
    //     visible: false,
    //     source: new XYZ({
    //         url: 'http://mt0.google.com/vt/lyrs=y&hl=en&x={x}&y={y}&z={z}&s=Ga'
    //     })
    // });

    // 订阅队列
    subscriptions: Subscription[] = [];
    postcomposes = new Map();

    MaxZoom = 20;
    MinZoom = 8;

    featureData: FeatureType | Array<FeatureType> = null;
    currentFeature = null;
    clustrOverlayType: MARKER_TYPE;
    clusterMarkTypes: MARKER_TYPE[] = [MARKER_TYPE.EQ_LEGEND_MARKER, MARKER_TYPE.IR_LEGEND_MARKER];

    viewIndexArr: any[] = [];
    viewStep = 0;
    viewChangeCount = 0;
    isShowSearch = false;
    keyWords = null;
    searchOption: Array<{ label: string; value: number }> = [
        {
            label: 'VMS',
            value: 0
        },
        {
            label: 'VD',
            value: 1
        },
        {
            label: 'CCTV',
            value: 3
        },
        {
            label: 'TSC',
            value: 4
        },
        {
            label: 'Zone',
            value: 2
        },
        {
            label: 'Road',
            value: 5
        }
    ];
    searchType = 0;
    trafficDataLayer = null;
    zoneAssignment = [];
    zoneList: number[] = [];
    isLoacteButtonShow = true;

    zoneParams: number[] = [];
    CreateEvent = CreateEvent;

    constructor(
        private route: ActivatedRoute,
        private titleService: Title,
        private mapLayerService: MapLayerService,
        private mapClusterService: MapClusteredService,
        private mapViewService: MapViewService,
        private bully: BullySubjectService,
        private translate: TranslateService,
        private nzModal: NzModalService,
        private systemService: SystemService,
        private mapDataService: MapDataService,
        private mapOverlayService: MapOverlayService,
        private tools: ToolsService,
        private msg: NotificationService,
        private message: NzMessageService,
        private ls: LoginService,
        private DMService: DataManagementService,
        private pub: PublicService
    ) {
        // 语言服务
        this.systemService.langSet();

        // 初始化区域权限
        this.getZoneIdListByUser();
    }

    ngOnInit() {
        // 判断是否为谷歌浏览器，若是就隐藏定位按钮。谷歌浏览器禁用了浏览器的定位功能。
        const ischrome = window.navigator.userAgent.indexOf('Chrome') > -1;
        const isEdge = window.navigator.userAgent.indexOf('Edge') > -1;
        if (ischrome && !isEdge) {
            this.isLoacteButtonShow = false;
        }
        // 判断本地token是否需要用户登录
        if (!this.ls.autoAccessToken()) {
            console.warn('token failure, please login!');
        }

        // 设置创库title
        this._setTitle();

        // 初始化主地图
        this.initMap();

        // 地理定位
        // this.geolocation();

        // 消息管理(包括全部订阅和初始化时发送消息)
        this._mapMessageManage();

        // 订阅stomp ws 事件
        const subsription = this.bully.getSubject().subscribe(res => {
            if (this.map) {
                // alarm
                if (res['type'] === SYSTEM_EVENT.ALARM_EVENT) {
                    const features = res['data'];

                    const coordinates = [
                        this.tools.calc(features, 'longitude', 107.085197),
                        this.tools.calc(features, 'latitude', 20.952057)
                    ];

                    this.setMarker(MARKER_TYPE.EQUIP_ALARM_MARKER, {
                        coordinates,
                        features
                    });
                }

                // alert
                if (res['type'] === SYSTEM_EVENT.ALERT_EVENT) {
                    const isAck = localStorage.getItem('alertSwitch');
                    if (!isAck) {
                        return;
                    }
                    const features = res['data'];

                    const coordinates = [
                        this.tools.calc(features, 'longitude', 107.085197),
                        this.tools.calc(features, 'latitude', 20.952057)
                    ];

                    this.setMarker(MARKER_TYPE.ALERT_MARKER, {
                        coordinates,
                        features
                    });
                }
            }
        });
        this.subscriptions.push(subsription);
    }

    ngAfterViewInit(): void {
        // 注册overlay
        this._registerOverlay();

        window.onunload = () => {
            // 发送gis窗口关闭的消息, 削减gis窗口数量
            this._mapWinOpt(false);
        };
    }

    ngOnDestroy(): void {
        if (this.subscriptions.length > 0) {
            this.subscriptions.forEach(sub => sub.unsubscribe());
        }
        this.bully.closeBroadcast(MESSAGE_CHANNEL.CCM_CHANNEL);
        this.bully.closeBroadcast(MESSAGE_CHANNEL.MAP_CHANNEL);
    }

    private _setTitle() {
        this.subscriptions.push(
            this.route.data.subscribe(res => {
                this.titleService.setTitle(res['title']);
            })
        );
    }

    // 初始化地图
    initMap() {
        // view
        this.currentCoords = this.mapViewService.centerCoords;
        const view = new View({
            center: this.currentCoords,
            // center: [107.07791, 20.96118],
            // center: [-73.965528, 40.783146],
            zoom: 16,
            projection: 'EPSG:4326',
            minZoom: this.MinZoom,
            maxZoom: this.MaxZoom
        });

        // basic_layer - RasterLayer(光栅,电子地图)
        const mapBasicLayer = this.mapViewService.getBasicMapLayerGeo();
        // locate_marker_layer
        /* const mapLocateMarkerLayer = new VectorLayer({
            source: this.mapLayerService.locate_marker({ coordinate: null }),
            zIndex: 30
        }); */
        const mapMarkerLayer = new VectorLayer({
            source: new VectorSource(),
            zIndex: 30
        });

        const mapRoadLayer = new VectorLayer({
            source: new VectorSource(),
            style: new Style({
                stroke: new Stroke({
                    color: 'red',
                    width: 7,
                    opacity: 1,
                    lineDash: [0.7, 6]
                })
            }),
            zIndex: 20
        });
        // const zoneLayer = this.mapViewService.getBasicMapLayer();

        // 设备报警 弹框
        /* const overlayOfTrafficSignal = new Overlay({
            element: document.getElementById('trafficSignal'),
            positioning: 'center-center',
            autoPan: true
        }) */

        // 事件报警 弹框
        /* const higtlightMapIconsOfOverlay = new Overlay({
            element: document.getElementById('highLightMapIcon'),
            autoPan: true,
            autoPanAnimation: {
                duration: 250
            }
        }); */

        // 初始化Operational Alarm 图标图层
        // const operationalAlarmIconsVector = this.mapClusterService.returnOperationAlarm();

        // 初始化Operational Alert 图标图层
        // const operationalAlertIconsVector = this.mapClusterService.returnOperationAlert();

        // const googleLayerHybrid = this.googleLayerHybrid;

        // 把图层放入LAYERS集合中
        this._layersMap.set(BASIC_LAYER_KEY.BASIC_LAYER, mapBasicLayer);
        this._layersMap.set(BASIC_LAYER_KEY.MARKER_LAYER, mapMarkerLayer);
        this._layersMap.set(BASIC_LAYER_KEY.ROAD_LAYER, mapRoadLayer);

        const layers = [
            mapBasicLayer,
            mapMarkerLayer,
            mapRoadLayer
            // googleLayerHybrid,
            // zoneLayer
        ];
        // controls
        const scaleLineControl = new ScaleLine();
        scaleLineControl.setUnits('metric');
        const controls = defaultControls({ attribution: false }).extend([scaleLineControl]);

        // interactions
        const interactions = defaultInteractions();

        // projection
        const projection = 'EPSG:4326';

        this.mapOptions = {
            target: 'mainMap',
            controls,
            interactions,
            projection,
            layers,
            view
        };
        try {
            this.map = new OLMAP(this.mapOptions);
        } catch (ex) {
            // console.warn('地图初始化失败', ex);
        }

        // 隐藏除底图外的其他图层
        this._layersMap.get(BASIC_LAYER_KEY.MARKER_LAYER).setVisible(false);

        // 挂载地图事件
        this._registerMapEvent();
        this.getAllZoneList();
        // 注册功能性图层
        const legendsTree = legendsData;
        this._interactionLayerHandle(legendsTree);
    }

    getAllZoneList() {
        this.DMService.getAllEnumInfo().subscribe(res => {
            if (res.code === '000000') {
                this.pub.optionsList = JSON.parse(JSON.stringify(res.data));
                const data = [];
                res.data.forEach(ele => {
                    if (ele.category === 'zone') {
                        ele.title = ele.name;
                        ele.key = ele.value;
                        ele.isLeaf = true;

                        data.push(ele);
                        this.zoneList.push(+ele.value);
                    }
                });
                this.zoneAssignment = data;
            }
        });
    }

    getZoneIdListByUser() {
        const queryData = {
            condition: {
                userId: localStorage.getItem('user_id'),
                user_Name: localStorage.getItem('user_name'),
                user_Pwd: null,
                organization_Id: null,
                userRole_Id: null,
                createTime: {
                    startTime: null,
                    endTime: null
                },
                updateTime: {
                    startTime: null,
                    endTime: null
                }
            },
            pageNum: 1,
            pageSize: 999999
        };
        this.DMService.getAllUser(queryData).subscribe(res => {
            const userZone = (res.content.content && res.content.content.length && res.content.content[0].userZoneRel) || [];
            this.systemService.userZoneList = userZone.map(zone => ({
                id: zone.vnqn_zone_id,
                isTemp: false
            }));
        });
    }

    // 图层显示隐藏
    layersShowHide(obj: NzTreeNode) {
        const category = obj['origin']['layerCategory'];
        const checked = obj['origin']['checked'];
        const isLayer = obj['origin']['isLayer'];
        const isLeaf = obj['origin']['isLeaf'];
        if (!isLayer && !isLeaf) {
            // 如果既不是图层又不是叶子节点,往下找图层
            /* if (obj.children && obj.children.length > 0) {
				for (const child of obj.children) {
					this.layersShowHide(child);
				}
			} */

            // 确定为Equipmentlayer的二级菜单
            this.equipmentLayerLvl2Handle(obj);
            return;
        }

        // checked = false
        if (!checked && isLayer && category !== ACTION_LAYER_KEY.ZONE) {
            this.switchLayer(category, checked);
            return;
        }

        if (category === ACTION_LAYER_KEY.INCIDENT_RECORD) {
            this.incidentLayerSwitchHandle(obj, isLeaf);
        } else if (category === ACTION_LAYER_KEY.EQUIPMENT) {
            this.equipmentLayerSwitchHandle(obj, isLeaf);
        } else if (category === ACTION_LAYER_KEY.TRAFFIC_DATA) {
            // this.switchLayer(category, true);
            this.processTrafficLayer(obj, true, category);
        } else if (category === ACTION_LAYER_KEY.AVL) {
        } else if (category === ACTION_LAYER_KEY.ZONE) {
            this.zoneLayerSwitchHandle(obj, isLeaf, category);
            // this._registerZoneLayer()
        } else {
            // LAYER_CATEGORY.USER_DEFINE_ZONE
        }
    }

    // 专门处理zone的layer的显示切换
    zoneLayerSwitchHandle(obj: NzTreeNode, isLeaf: boolean, key: ACTION_LAYER_KEY) {
        this.processZoneLayer(obj, isLeaf, key);
    }

    processTrafficLayer(cag, isLeaf: boolean, key: ACTION_LAYER_KEY) {
        const layer = this.mapViewService.getTrafficDataLayer(true);
        this._layersMap.set('Traffic_Data', layer);
        this.map.addLayer(layer);
        if (cag['isChecked']) {
            layer.setVisible(true);
        } else {
            layer.setVisible(false);
        }
    }

    processZoneLayer(node, isLeaf: boolean, key: ACTION_LAYER_KEY, param?) {
        let layer = this._layersMap.get(ACTION_LAYER_KEY.ZONE);
        if (!layer) {
            layer = this.mapViewService.getZoneLayer(true);
            this.map.addLayer(layer);
            this._layersMap.set(ACTION_LAYER_KEY.ZONE, layer);
        }
        if (isLeaf) {
            layer.setVisible(true);
            const id = node['origin']['typeCode'] as number;
            if (node['isChecked']) {
                this.zoneParams = [...new Set([...this.zoneParams, id])];
            } else {
                const idx = this.zoneParams.findIndex(i => i === id);
                this.zoneParams.splice(idx, 1);
                if (!this.zoneParams.length) {
                    layer.setVisible(false);
                    return;
                }
            }
            layer.getSource().updateParams({ FEATUREID: this.zoneParams.join(',') });
            return;
        }
        if (node['isChecked']) {
            this.zoneParams = [...this.zoneList];
            layer.getSource().updateParams({ FEATUREID: null });
            layer.setVisible(true);
        } else {
            this.zoneParams = [];
            layer.setVisible(false);
        }
    }

    searchZoneLayer(key: ACTION_LAYER_KEY, param?) {
        let layer = this._layersMap.get(ACTION_LAYER_KEY.ZONE);
        if (!layer) {
            layer = this.mapViewService.getZoneLayer(true);
            this.map.addLayer(layer);
            this._layersMap.set(ACTION_LAYER_KEY.ZONE, layer);
        }
        layer.setVisible(true);
        if (param) {
            this.zoneParams = param;
            layer.getSource().updateParams({ FEATUREID: this.zoneParams });
            return;
        } else {
            const idx = this.zoneParams.findIndex(i => i === param);
            this.zoneParams.splice(idx, 1);
            if (!this.zoneParams.length) {
                layer.setVisible(false);
            }
        }
        layer.getSource().updateParams({ FEATUREID: this.zoneParams.join(',') });
        layer.getSource().updateParams({ FEATUREID: null });
        layer.setVisible(true);
    }

    // processZoneLayerChildren(id: any) {
    //     const layer = this._layersMap.get(ACTION_LAYER_KEY.ZONE);
    //     if(!layer) {
    //         return;
    //     }

    //     if (node['isChecked']) {
    //         layer.setVisible(true);
    //     } else {
    //         layer.setVisible(false);
    //     }
    //     layer.getSource().updateParams({ FEATUREID: id });
    // }

    // 专门处理incident的layer的显示切换
    incidentLayerSwitchHandle(obj: NzTreeNode, isLeaf: boolean) {
        const category = obj['origin']['layerCategory'];
        if (isLeaf) {
            const checkedTypeCodes = obj.parentNode.children
                .filter(child => child.isChecked)
                .reduce((p, c) => [...p, c.origin.typeCode], []);
            if (checkedTypeCodes.length === 0) {
                // 说明这个layer没有选中任何feature,直接隐藏
                this.switchLayer(category, false);
                return;
            }
            this.mapClusterService.getIncidentVectorSource(checkedTypeCodes).subscribe(source => this.switchLayer(category, true, source));
        } else {
            this.mapClusterService.getIncidentVectorSource().subscribe(source => this.switchLayer(category, true, source));
        }
    }

    // 专门处理equipment的layer的显示切换
    equipmentLayerSwitchHandle(obj: NzTreeNode, isLeaf: boolean) {
        const category = obj['origin']['layerCategory'];

        if (isLeaf) {
            this.equipmentLayerLvl2Handle(obj);
        } else {
            this.mapClusterService.getEquipmentVectorSource().subscribe(source => this.switchLayer(category, true, source));
        }
    }

    // equipmentlayer切换显示的2级菜单处理
    equipmentLayerLvl2Handle(obj: NzTreeNode) {
        const category = obj['origin']['layerCategory'];
        const treeCom = this.legendsCom.treeCom;
        const checkedNodes = this.tools
            .treeFlat(treeCom.getCheckedNodeList())
            .filter(ckn => ckn.origin.layerCategory === ACTION_LAYER_KEY.EQUIPMENT); // 过滤掉其他图层
        if (checkedNodes.length === 0) {
            this.switchLayer(category, false);
            return;
        }
        const typeCodes = [...new Set([...checkedNodes.reduce((p, c) => [...p, c.origin.typeCode], [])])];
        const typePlusStatus = checkedNodes.reduce((p, c) => [...p, `${c.origin.typeCode}_${c.origin.status}`], []);

        this.mapClusterService.getEquipmentVectorSource(typeCodes, typePlusStatus).subscribe(source => {
            this.switchLayer(category, true, source);
        });
    }

    // 切换图层
    switchLayer(key: ACTION_LAYER_KEY, isShow: boolean, vectorSource?: any) {
        const layer = this._layersMap.get(key);
        if (layer) {
            /* if (isShow) {
				if (vectorSource) {
					layer.setSource(null);
					layer.setSource(vectorSource);
				}
				layer.setVisible(isShow);
			} else {
				layer.setVisible(false);
			} */
            if (vectorSource) {
                layer.setSource(null);
                layer.setSource(vectorSource);
            }

            layer.setVisible(isShow);
        }
    }

    // 清除
    clear() {
        if (!this.legendsCom) {
            return;
        }
        this.closeOverlay();
        this.closePostCompose();
        for (const [key, layer] of this._layersMap.entries()) {
            if (key === BASIC_LAYER_KEY.BASIC_LAYER) {
                continue;
            }
            const source = layer.getSource();
            if (source && source.clear instanceof Function) {
                source.clear();
            }
            layer.setVisible(false);
        }

        this.legendsCom.treeData = this.tools.isClone(legendsData);
    }

    // 关闭所有弹窗
    closeOverlay() {
        for (const overlay in this.overlayIsShow) {
            if (this.overlayIsShow.hasOwnProperty(overlay)) {
                this.overlayIsShow[overlay] = false;
            }
        }
        for (const overlay of this._overlayMap.values()) {
            overlay.setPosition(undefined);
        }
    }

    // 标记定位中心点
    center(coordinates: number[]): void {
        const view = this.map.getView();
        if (!view) {
            return;
        }
        // 关闭所有弹窗
        // this.closeOverlay();
        view.setCenter(coordinates);
    }

    // 设置定位点 locate
    setLocateMarker(coordinates: number[]) {
        const features: FeatureType = {
            longitude: coordinates[0].toPrecision(9),
            latitude: coordinates[1].toPrecision(9),
            linkID: '',
            roadName: '',
            available: false
        };

        // 查询地理位置信息
        this.mapDataService.getLocalInfo(coordinates).subscribe(res => {
            if (this.tools.calc(res, 'features', []).length > 0) {
                const props = res.features[0].properties;
                features.available = true;
                features.linkID = props.linkID;
                features.roadName = props.name;
            }
            // 获取坐标到IR detail
            if (features.available) {
                this.getPositionToIRdetail(features);
            } else {
                this.msg.notify({
                    type: 'warning',
                    path: 'Gis.Gis.Create_Notify'
                });
            }
            this.setMarker(MARKER_TYPE.LOCATE_MARKER, {
                coordinates,
                features
            });
        });
    }

    // 获取地理定位
    geolocation() {
        this.geoLoading = true;
        this.mapViewService
            .createLocationObservable()
            .pipe(retry(5))
            .subscribe(
                data => {
                    this.geoLoading = false;
                    this.currentCoords = [
                        this.tools.calc(data, 'coords.longitude', 107.085197),
                        this.tools.calc(data, 'coords.latitude', 20.952057)
                    ];
                    this.center(this.currentCoords);
                    // set locate marker
                    this.setLocateMarker(this.currentCoords);
                },
                err => {
                    /* this.msg.notify({
						type: 'warning',
					}) */
                    alert('locate failed!');
                    this.geoLoading = false;
                }
            );
    }

    /**
     * set marker
     * @param type MARKER_TYPE
     * @param options 特征数据
     */
    setMarker(type: MARKER_TYPE, options: MarkerOption) {
        this.closeOverlay();

        const features = this.mapLayerService.generateMarkerFeatures(type, options);
        this.addfeatures(type, options, features);
    }

    addfeatures(type: MARKER_TYPE, options: MarkerOption, features) {
        const layer = this._layersMap.get(BASIC_LAYER_KEY.MARKER_LAYER);
        // layer.setSource(source);

        const source = layer.getSource();
        if (type === MARKER_TYPE.LOCATE_MARKER) {
            const oldFeatures = source.getFeatures();
            oldFeatures.forEach(feature => {
                // 如果是 locate 只允许出现一个
                if (feature['values_']['name'] === MARKER_TYPE.LOCATE_MARKER) {
                    source.removeFeature(feature);
                }
            });
        } else {
            source.clear();
        }
        source.addFeatures(features);
        layer.setVisible(true);
        if (type !== MARKER_TYPE.LOCATE_MARKER) {
            this.center(options.coordinates);
        }
    }

    setResMarker(type: MARKER_TYPE, options: MarkerOption) {
        this.closeOverlay();

        const features = this.mapLayerService.generateMarkerFeatures(type, options);
        this.newFeatures.push(features);
        const layer = this._layersMap.get(BASIC_LAYER_KEY.MARKER_LAYER);
        // layer.setSource(source);

        const source = layer.getSource();
        if (type === MARKER_TYPE.LOCATE_MARKER) {
            const oldFeatures = source.getFeatures();
            oldFeatures.forEach(feature => {
                // 如果是 locate 只允许出现一个
                if (feature['values_']['name'] === MARKER_TYPE.LOCATE_MARKER) {
                    source.removeFeature(feature);
                }
            });
        }
        source.clear();
        source.addFeatures(this.newFeatures);
        layer.setVisible(true);

        if (type !== MARKER_TYPE.LOCATE_MARKER) {
            this.center(options.coordinates);
        }
    }

    /**
     * delete current marker
     */
    deleteMarker() {
        if (!this.currentFeature) {
            return;
        }
        const layer = this._layersMap.get(BASIC_LAYER_KEY.MARKER_LAYER);
        const source = layer.getSource();
        source.removeFeature(this.currentFeature);

        // 停止报警动画
        this.stopFlash(this.featureData);
    }

    /**
     * stop falsh 并且直接返回当前Key
     */
    stopFlash(data: any) {
        // const id = data.id;
        const long = (+data.longitude || 0).toPrecision(6);
        const lat = (+data.latitude || 0).toPrecision(6);
        const key = `${long}_${lat}`;

        // 如果在同一位置，取消之前的动画，开始新的动画
        if (this.postcomposes.has(key)) {
            unByKey(this.postcomposes.get(key));
        }
        return key;
    }
    // 地图创建事件
    async createEvent(event: CreateEvent) {
        if (!this._checkCanCreate()) {
            return;
        }
        const posX = (this.featureData as FeatureType).latitude;
        const posY = (this.featureData as FeatureType).longitude;
        const zoneId = await this.mapDataService.getZoneIdFromGis({ posX, posY }).toPromise();
        const zoneIds = this.systemService.userZoneList.map(z => z.id);

        if (!zoneIds.includes(+zoneId)) {
            this.message.error('no permission');
            return;
        }
        const data: CreateEventOptData = CreateEventMap.get(event);
        const bully = {
            type: SYSTEM_EVENT.CCM_NAVIGATE,
            data: {
                module: data.module,
                pageKey: data.pageKey,
                path: data.path,
                data: { ...this.featureData, zoneID: +zoneId }
            }
        };
        this.bully.registerBroadcastSend(MESSAGE_CHANNEL.MAP_CHANNEL, bully);

        // 删除标点
        this.deleteMarker();
        this.closeOverlay();
    }
    // 获取坐标到IR detail
    getPositionToIRdetail(features) {
        if (this.comfrom) {
            this.nzModal.confirm({
                nzTitle: '<i>Do you Want to send this coordinate to CCM?</i>',
                nzContent: `<b>coordinate: ${features.latitude},${features.longitude}</b>`,
                nzOnOk: () => {
                    const data: Bully = { type: MESSAGE_CHANNEL.MAP_CHANNEL, data: { features, dataType: this.comfrom } };
                    this.bully.registerBroadcastSend(MESSAGE_CHANNEL.MAP_CHANNEL, data);
                    this.comfrom = null;
                }
            });
        }
    }

    // 关闭postcompose动画
    closePostCompose() {
        if (this.postcomposes.size > 0) {
            for (const listener of this.postcomposes.values()) {
                unByKey(listener);
            }
        }
    }

    // alert operational
    alertOperation(_e: boolean) {
        if (_e) {
            this.createEvent(CreateEvent.Incident);
        } else {
            this.deleteMarker();
        }
        this.closeOverlay();
    }

    // 填充视图备份数组, 更新viewStep
    fillViewBackup(e) {
        const center = e.target.values_.center;
        const zoom = e.target.getZoom();
        const obj = {
            center,
            zoom
        };
        this.viewIndexArr.push(obj);
        if (this.viewChangeCount % 2 === 0) {
            if (this.viewIndexArr.length > 1) {
                this.viewIndexArr.length -= 1;
            }
        } else {
            // 不是首次变动,并且在队列退回操作中新加入了操作,那么就只留下退到的这个视图和新加的视图了
            if (this.viewChangeCount > 1 && this.viewStep !== this.viewIndexArr.length - 2) {
                // 这里-2是因为前面有新的push
                this.viewIndexArr = [...this.viewIndexArr[this.viewStep], this.viewIndexArr[this.viewIndexArr.length - 1]];
            }
            this.viewStep = this.viewIndexArr.length - 1;
        }
        if (this.viewIndexArr.length > 19) {
            this.viewIndexArr = this.viewIndexArr.slice(10);
            this.viewStep = this.viewIndexArr.length - 1;
        }
    }

    // 前往历史view
    gotoHistroy(dir: 'next' | 'prev') {
        if (dir === 'next') {
            if (this.viewIndexArr.length === 0 || this.viewStep === this.viewIndexArr.length - 1) {
                return;
            }
            this.viewStep++;
        } else {
            if (this.viewStep === 0) {
                return;
            }
            this.viewStep--;
        }
        const viewObj = this.viewIndexArr[this.viewStep];
        this.resetView(viewObj);
    }

    // 重设视图属性
    resetView({ center, zoom }: { center: number[]; zoom: number }) {
        if (!center || !zoom) {
            return;
        }
        const view = this.map.getView();
        if (view) {
            view.setCenter(center);
            view.setZoom(zoom);
        }
    }

    // 检查是否可执行创建
    private _checkCanCreate(): boolean {
        const featureAvailable = this.featureData['available'];
        if (!featureAvailable) {
            this.msg.notify({
                type: 'warning',
                path: 'Gis.Gis.Create_Notify'
            });
            return false;
        }

        const zoom = this.map.getView().getZoom();
        if (zoom < 19) {
            this.msg.notify({
                type: 'error',
                path: 'Gis.Gis.Zoom_Notify'
            });
            return false;
        }

        return true;
    }

    private _registerOverlay() {
        // locate marker menu
        this._generaterAndAddOverlay(OVERLAY_KEY.LOCATE_MARKER_OVERLAY);

        // alert overlay
        this._generaterAndAddOverlay(OVERLAY_KEY.ALERT_OVERLAY);

        // cluster features overlay
        this._generaterAndAddOverlay(OVERLAY_KEY.CLUSTER_FEATURES_OVERLAY);

        // incident overlay
        this._generaterAndAddOverlay(OVERLAY_KEY.INCIDENT_OVERLAY);

        // equipment overlay
        this._generaterAndAddOverlay(OVERLAY_KEY.EQUIPMENT_OVERLAY);
    }

    private _generaterAndAddOverlay(typeKey: OVERLAY_KEY) {
        const ele = document.getElementById(typeKey);
        const overlay = this.mapOverlayService.generaterOverlayByType(typeKey, ele);
        this._overlayMap.set(typeKey, overlay);
        this.map.addOverlay(overlay);
    }

    // 挂载地图事件
    private _registerMapEvent() {
        // 点击地图事件
        this.map.on('click', evt => {
            // 关闭所有弹窗
            this.closeOverlay();
            const feature = this.map.forEachFeatureAtPixel(
                evt.pixel,
                f => f /* , {
				layerFilter: layer => layer === this._layersMap.get(BASIC_LAYER_KEY.LOCATE_MARKER_LAYER)
			} */
            );
            if (!feature) {
                // set locate marker
                this.setLocateMarker(evt.coordinate);
            }

            if (feature) {
                let type = this.tools.calc(feature, 'values_.prototype.data.type', '');

                if (!type) {
                    type = this.tools.calc(feature, 'values_.features.0.values_.prototype.data.type', '');
                }
                if (type && type !== MARKER_TYPE.LOCATE_MARKER) {
                    this._showOverlay(type, feature);
                }
            }
        });

        // 针对feature的右键事件
        this.map.on('contextmenu', _evt => {
            _evt.preventDefault();
            this.closeOverlay();

            const feature = this.map.forEachFeatureAtPixel(_evt.pixel, f => f);
            if (feature) {
                const type = this.tools.calc(feature, 'values_.prototype.data.type', '');
                if (type === MARKER_TYPE.LOCATE_MARKER) {
                    // 右键只有locat marker会弹窗
                    this._showOverlay(type, feature);
                }
            }
        });

        // 地图视图变化事件
        this.map.getView().on('change', _evt => {
            this.fillViewBackup(_evt);
            this.viewChangeCount++;
            if (this.viewChangeCount > 9) {
                this.viewChangeCount = 0;
            }
        });

        // marker layer的source 增加compose事件
        this._layersMap
            .get(BASIC_LAYER_KEY.MARKER_LAYER)
            .getSource()
            .on('addfeature', e => {
                const name = e['feature']['values_']['name'];

                if (name === MARKER_TYPE.EQUIP_POS_MARKER || name === MARKER_TYPE.RESPONSE_MARKER) {
                    // 设备定位动画
                    this._featureFlash('position', e.feature);
                }

                if (name === MARKER_TYPE.ALERT_MARKER || name === MARKER_TYPE.EQUIP_ALARM_MARKER || name === MARKER_TYPE.INCIDENT_MARKER) {
                    this._featureFlash('event', e.feature);
                }
            });
    }

    // show overlay (此方法只用于点marker的时候)
    private _showOverlay(type: MARKER_TYPE, feature: any): void {
        const _map = {
            [MARKER_TYPE.LOCATE_MARKER]: OVERLAY_KEY.LOCATE_MARKER_OVERLAY,
            [MARKER_TYPE.ALERT_MARKER]: OVERLAY_KEY.ALERT_OVERLAY,
            [MARKER_TYPE.EQ_LEGEND_MARKER]: OVERLAY_KEY.EQUIPMENT_OVERLAY,
            [MARKER_TYPE.EQUIP_ALARM_MARKER]: OVERLAY_KEY.EQUIPMENT_OVERLAY,
            [MARKER_TYPE.EQUIP_POS_MARKER]: OVERLAY_KEY.EQUIPMENT_OVERLAY,
            [MARKER_TYPE.IR_LEGEND_MARKER]: OVERLAY_KEY.INCIDENT_OVERLAY,
            [MARKER_TYPE.INCIDENT_MARKER]: OVERLAY_KEY.INCIDENT_OVERLAY,
            [MARKER_TYPE.RESPONSE_MARKER]: OVERLAY_KEY.RESPONSE_OVERLAY
        };
        // get features data

        if (this.clusterMarkTypes.includes(type)) {
            // clusterMarkTypes
            this.featureData = this.tools
                .calc(feature, 'values_.features', [])
                .reduce((p, c) => [...p, c.values_.prototype.data.render], []);
        } else {
            this.featureData = feature['values_']['prototype']['data']['render'];
        }
        this.currentFeature = feature;
        let overlayKey = _map[type];
        // 如果得到featureData是数组,且length > 1
        if (isArray(this.featureData)) {
            /* const zoom = this.map.getView().getZoom();
			if (zoom < 19) {
				this.msg.notify({
					type: 'error',
					path: 'Gis.Gis.Zoom_Notify'
				});
				return;
			} */
            if (this.featureData.length > 1) {
                this.clustrOverlayType = type;
                overlayKey = OVERLAY_KEY.CLUSTER_FEATURES_OVERLAY;
            } else if (this.featureData.length === 1) {
                this.featureData = this.featureData[0];
            }
        }
        // if (overlayKey === 'response-overlay') {
        //     overlayKey = OVERLAY_KEY.CLUSTER_FEATURES_OVERLAY;
        // }
        const overlay = this._overlayMap.get(overlayKey);
        if (overlay) {
            const coordinates = feature.getGeometry().getCoordinates();
            overlay.setPosition(coordinates);
            setTimeout(() => (this.overlayIsShow[overlayKey] = true));
        }
    }

    // 点击cluster弹窗的列表项开窗
    public showOverlayFromCluster({ type, feature }: { type: MARKER_TYPE; feature: any }) {
        this.closeOverlay();
        const _map = {
            [MARKER_TYPE.EQ_LEGEND_MARKER]: OVERLAY_KEY.EQUIPMENT_OVERLAY,
            [MARKER_TYPE.IR_LEGEND_MARKER]: OVERLAY_KEY.INCIDENT_OVERLAY
        };
        this.featureData = feature;
        this.currentFeature = null;
        const overlayKey = _map[type];
        let coordinates = null;
        const overlay = this._overlayMap.get(overlayKey);
        if (overlay) {
            if (type === MARKER_TYPE.EQ_LEGEND_MARKER) {
                coordinates = [feature.longitude, feature.latitude];
            } else {
                coordinates = [feature.start_X_Coor, feature.start_Y_Coor];
            }
            overlay.setPosition(coordinates);
            setTimeout(() => (this.overlayIsShow[overlayKey] = true));
        }
    }

    closeSpecificOverlay(key: OVERLAY_KEY) {
        const overlay = this._overlayMap.get(key);
        if (overlay) {
            overlay.setPosition(undefined);
            this.overlayIsShow[key] = false;
        }
    }

    /**
     * feature animation (定位和报警动画)
     * @param type 'position' | 'event' (event包括alert和alarm)
     * @param feature 特征数据
     */
    private _featureFlash(type: 'position' | 'event', feature: any) {
        const data = this.tools.calc(feature, 'values_.prototype.data.render', '');
        if (!data) {
            return;
        }

        // 停止重复的动画
        const key = this.stopFlash(data);

        // this.closePostCompose();
        let start = new Date().getTime();
        const duration = 800;
        const listenerKey = this.map.on('postcompose', event => {
            const vectorContext = event.vectorContext;
            const frameState = event.frameState;
            const flashGeom = feature.getGeometry().clone();
            const elapsed = frameState.time - start;
            const elapsedRatio = elapsed / duration;

            const raidus = easeOut(elapsedRatio) * 20 + 5;
            const opacity = easeOut(0.8 - elapsedRatio);

            if (raidus > 30) {
                start = new Date().getTime();
            }

            const _style = new Style({
                image: new CircleStyle({
                    radius: raidus,
                    stroke: new Stroke({
                        color: type === 'position' ? `rgba(64,169,255,${opacity})` : `rgba(251,52,58,${opacity})`,
                        width: 20 + opacity
                    })
                })
            });

            vectorContext.setStyle(_style);
            vectorContext.drawGeometry(flashGeom);

            this.map.render();
        });

        this.postcomposes.set(key, listenerKey);
    }

    // 拿到设备图层的源然后显示图层
    /* private _getEquipmentVectorSource(obj: NzTreeNode, key: string) {
		const equipmentInfo = obj['origin']['icon'].split('_');
		const type = equipmentInfo[0].toLowerCase() as EQUIPMENT;
		const status = equipmentInfo[1];
		this.mapDataService.getEquipmentFeatureData(type).subscribe(res => {
			const features = [];
			this.tools
				.calc(res, 'features', [])
				.filter(feature => this.tools.calc(feature, 'properties.status_code', 'Out') === status)
				.forEach(feature => {
					const props = feature['properties'];
					const temporary = new Feature();
					temporary.values_ = props;
					temporary.values_.geometry = new Point([props.longitude, props.latitude]);
					const iconSrc = `content/images/icons/${props.eqt_type}_${props.status_code}.png`;
					temporary.prototype = {
						iconSrc,
						data: {
							type: props.eqt_type,
							render: props
						}
					};
					features.push(temporary);
				});
			const vectorSource = new Cluster({
				distance: 40,
				source: new VectorSource({
					features
				})
			});
			this._switchLayer(key, true, vectorSource);
		});
	} */

    // 递归处理legends上面的图层
    private _interactionLayerHandle(legendsTree) {
        for (const legend of legendsTree) {
            if (legend['isLayer'] === true) {
                const category = legend['layerCategory'];
                if (category === ACTION_LAYER_KEY.INCIDENT_RECORD) {
                    this._registerIncidentLayer(legend);
                } else if (category === ACTION_LAYER_KEY.EQUIPMENT) {
                    this._registerEquipmentLayer(legend);
                } else if (category === ACTION_LAYER_KEY.TRAFFIC_DATA) {
                    // this._registerTrafficLayer(legend);
                } else if (category === ACTION_LAYER_KEY.AVL) {
                } else if (category === ACTION_LAYER_KEY.ZONE) {
                } else {
                    // LAYER_CATEGORY.USER_DEFINE_ZONE
                }
            }
            /* else {
				if (legend.children && legend.children.length > 0) {
					this._interactionLayerHandle(legend.children);
				}
			} */
        }
    }

    // 注册事件图层
    private _registerIncidentLayer(legend) {
        const key = legend['layerCategory'];
        const layer = this.mapClusterService.returnClusterLayer('incident');
        this._layersMap.set(key, layer);
        this.map.addLayer(layer);
    }

    // 注册设备图层
    private _registerEquipmentLayer(legend) {
        const key = legend['layerCategory'];
        const typeCode = legend['typeCode'];
        const layer = this.mapClusterService.returnClusterLayer('equipment', typeCode);
        this._layersMap.set(key, layer);
        this.map.addLayer(layer);
    }

    // 注册交通图层
    private _registerTrafficLayer(legend) {
        const key = legend['layerCategory'];
        const layer = this.mapViewService.getTrafficDataLayer(true);
        this._layersMap.set(key, layer);
        this.map.addLayer(layer);
    }

    // 注册区域图层
    // private _registerZoneLayer(legend) {
    //     const key = legend['layerCategory'];
    //     const layer = this.mapViewService.getTrafficDataLayer();
    //     this._layersMap.set(key, layer);
    //     this.map.addLayer(layer);
    // }

    // 地图消息订阅
    private _mapMessageManage() {
        // 设置语言
        this._languageSet();

        // 发送地图窗口打开的消息
        this._mapWinOpt(true);
        // 监听gis窗口是否重复打开
        const subscription = this.bully.registerBroadcastReceive(MESSAGE_CHANNEL.MAP_CHANNEL).subscribe(res => {
            if (res['type'] === SYSTEM_EVENT.MAP_WIN_CHANGE && res['data'] === true) {
                window.location.href = 'about:blank';
            }
        });
        this.subscriptions.push(subscription);

        // 监听ccm发送过来的消息
        this._watchCCMInformation();
    }

    // 设置语言
    private _languageSet() {
        const subscription = this.bully.registerBroadcastReceive(MESSAGE_CHANNEL.LANGUAGE_CHANNEL).subscribe(res => {
            if (!res) {
                return;
            }
            if (res['type'] !== SYSTEM_EVENT.LANG_CHANGE) {
                return;
            }
            const lang = res['data'];
            this.translate.use(lang ? lang : 'en');
        });
        this.subscriptions.push(subscription);
    }

    // 发送地图窗口状态的消息
    private _mapWinOpt(isOpen: boolean) {
        const data: Bully = { type: SYSTEM_EVENT.MAP_WIN_CHANGE, data: isOpen };
        this.bully.registerBroadcastSend(MESSAGE_CHANNEL.MAP_CHANNEL, data);
    }

    // 监听ccm发送过来的消息
    private _watchCCMInformation() {
        BROWSER_BROADCAST.addEventListener('message', res => {
            const bully = res.data as Bully;
            if (bully.type === SYSTEM_EVENT.ZONE_CHANGE_EVENT) {
                this.systemService.userZoneList = [...bully.data];
            }
        });

        const subscription = this.bully.registerBroadcastReceive(MESSAGE_CHANNEL.CCM_CHANNEL).subscribe(res => {
            // 监听ccm窗口是否关闭
            if (res['type'] === SYSTEM_EVENT.CCM_WIN_CHANGE && res['data'] === false) {
                window.close();
            }

            // 监听Alert ACK闪烁
            if (res['type'] === SYSTEM_EVENT.ACK_ALERT) {
                this.clear();
            }

            // 设备定位
            if (res['type'] === SYSTEM_EVENT.EQUIPMENT_POSITION) {
                const features = res['data'];
                // features.status = features.workStatus;
                // features.status = 'Active';
                features.deviceType = features.eqtType;

                const coordinates = [this.tools.calc(features, 'longitude', 107.085197), this.tools.calc(features, 'latitude', 20.952057)];
                // const coordinates = [104.061724, 30.625442];
                this.setMarker(MARKER_TYPE.EQUIP_POS_MARKER, {
                    coordinates,
                    features
                });
            }

            // alarm 设备报警
            if (res['type'] === SYSTEM_EVENT.ALARM_POSITION) {
                const features = res['data'];
                features.eqtId = features.deviceID;

                const coordinates = [this.tools.calc(features, 'longitude', 107.085197), this.tools.calc(features, 'latitude', 20.952057)];

                this.setMarker(MARKER_TYPE.EQUIP_ALARM_MARKER, {
                    coordinates,
                    features
                });
            }

            // incident
            if (res['type'] === SYSTEM_EVENT.INCIDENT_POSITION) {
                const features = res['data'];
                const coordinates = [
                    this.tools.calc(features, 'start_X_Coor', 107.085197),
                    this.tools.calc(features, 'start_Y_Coor', 20.952057)
                ];
                // const coordinates = [104.070142, 30.654698];
                this.setMarker(MARKER_TYPE.INCIDENT_MARKER, {
                    coordinates,
                    features
                });
            }

            // responsePlan
            if (res['type'] === SYSTEM_EVENT.RESPONSE_PLAN) {
                const statusObj = { OK: 'Active', Faulty: 'Failed' };
                const data = res['data'];
                const features = [];
                const center: MarkerOption = { coordinates: null, features: null };
                center.coordinates = [data.start_X_Coor, data.start_Y_Coor];
                data.cmdList.filter(item => item.sysID === '0').forEach(item => {
                    const { longitude, latitude, deviceType } = item.deviceDetailInfo;
                    item['longitude'] = longitude;
                    item['latitude'] = latitude;
                    const cords = longitude > latitude ? [longitude, latitude] : [latitude, longitude];
                    const featureParam = {
                        geometry: new Point(cords),
                        name: MARKER_TYPE.RESPONSE_MARKER,
                        prototype: {
                            data: {
                                type: MARKER_TYPE.RESPONSE_MARKER,
                                render: item
                            }
                        }
                    };
                    const status = statusObj[item.workStatus] || 'Active';
                    const styleParam = {
                        image: new Icon({
                            anchor: [0.5, 0.5],
                            anchorXUnits: 'fraction',
                            anchorYUnits: 'fraction',
                            src: `content/images/icons/equipment/${deviceType}_${status}.png`,
                            scale: 1.2
                        }),
                        text: new Text({
                            text: item.deviceID,
                            font: '12px "Arial", sans-serif',
                            textBaseline: 'middle',
                            offsetY: 20,
                            fill: new Fill({
                                color: '#555'
                            }),
                            stroke: new Stroke({
                                color: '#fff'
                            })
                        })
                    };
                    const iconStyle = new Style(styleParam);
                    const iconFeature = new Feature(featureParam);
                    iconFeature.setStyle(iconStyle);
                    features.push(iconFeature);
                });
                this.addfeatures(MARKER_TYPE.RESPONSE_MARKER, center, features);
            }

            // alert
            if (res['type'] === SYSTEM_EVENT.ALERT_POSITION) {
                const alertSwitch = JSON.parse(localStorage.getItem('alertSwitch'));
                if (!alertSwitch) {
                    return;
                }
                const features = res['data'];

                const coordinates = [this.tools.calc(features, 'longitude', 107.085197), this.tools.calc(features, 'latitude', 20.952057)];

                features.type = '0';

                this.setMarker(MARKER_TYPE.ALERT_MARKER, {
                    coordinates,
                    features
                });
            }
            // CCM获取地图位置
            if (res['type'] === MESSAGE_CHANNEL.CCM_CHANNEL) {
                this.comfrom = res['data']['data'];
                if (this.comfrom) {
                    // 删除标点
                    // this.deleteMarker();
                    // this.closeOverlay();
                    window.focus();
                }
            }
        });
        this.subscriptions.push(subscription);
    }

    toggleSearchButton() {
        this.isShowSearch = !this.isShowSearch;
        this.searchType = 0;
        this.keyWords = null;
        const layer = this._layersMap.get(BASIC_LAYER_KEY.ROAD_LAYER);
        if (layer) {
            layer.setSource(null);
            layer.setVisible(false);
        }
    }

    toggleDeviceType() {
        this.keyWords = null;
    }

    // 搜索
    onSearch(event) {
        event.preventDefault();
        event.stopPropagation();
        if (event.keyCode !== 13) {
            return;
        }
        if (this.searchType === null) {
            this.msg.notify({
                type: 'warning',
                path: 'Gis.Gis.validate_device_type'
            });
            return;
        }
        if (!this.keyWords) {
            this.msg.notify({
                type: 'warning',
                path: 'Gis.Gis.validate_key_words'
            });
            return;
        }
        if (this.searchType === 0 || this.searchType === 1 || this.searchType === 3 || this.searchType === 4) {
            this.getDeviceInfoByIdAndType();
        } else if (this.searchType === 2) {
            this.zoneParams = [];
            this.searchZoneLayer(ACTION_LAYER_KEY.ZONE, this.keyWords);
        } else if (this.searchType === 5) {
            const params = {
                roadName: this.keyWords.trim()
            };
            this.getRoad(params);
        }
    }

    getDeviceInfoByIdAndType(): void {
        const params = {
            fieldId: this.keyWords,
            deviceType: this.searchType
        };
        this.mapDataService.getDeviceInfoByIdAndType(params).subscribe(res => {
            if (res['code'] === '000000') {
                this.isShowSearch = false;
                this.keyWords = null;
                this.searchEquipment(res['data']);
            } else if (res['code'] === '999999') {
                this.msg.notify({
                    type: 'warning',
                    path: 'Gis.Gis.Search_Notify'
                });
            }
        });
    }

    getRoad(params) {
        this.mapDataService.getRoad(params).subscribe(res => {
            /*if (res['code'] === '000000') {
                if (res['data']) {
                    const string = res['data'];
                    const longitude = string.split(' ')[0].split('(')[1];
                    const latitude = string.split(' ')[1].split(')')[0];
                    const coordinates = [
                        this.tools.calc(longitude, 'longitude', 107.085197),
                        this.tools.calc(latitude, 'latitude', 20.952057)
                    ];
                    this.center(coordinates);
                    const markerOption = {
                        coordinates,
                        features: null
                    };
                    this.setMarker(MARKER_TYPE.LOCATE_MARKER, markerOption);
                    this.isShowSearch = false;
                    this.keyWords = null;
                } else {
                    this.msg.notify({
                        type: 'warning',
                        path: 'Gis.Gis.Road_Does_Not_Exist'
                    });
                }
            }*/
            const features = new GeoJSON().readFeatures(res);
            const source = new VectorSource({
                features
            });
            const roadLayer = this._layersMap.get(BASIC_LAYER_KEY.ROAD_LAYER);
            if (roadLayer) {
                roadLayer.setSource(null);
                roadLayer.setSource(source);
                roadLayer.setVisible(true);
            }
        });
    }

    searchEquipment(data) {
        const features = data;
        features.status = features.workStatus;
        // features.status = 'Active';
        features.deviceType = features.eqtType;
        const coordinates = [this.tools.calc(features, 'longitude', 107.085197), this.tools.calc(features, 'latitude', 20.952057)];
        this.setMarker(MARKER_TYPE.EQUIP_POS_MARKER, {
            coordinates,
            features
        });
    }

    runParent(msg) {}
}
